function h = cnn(data, bins)
% Choose nearest neighbors from bins.
% Input :
%   data - M * N * K matrix, M * N is image size or what ever, K is bit
%          numbers.
%   bins - P * K matrix
%
% Output:
%   h - nearest bins index
%
% Test-case:
% data(1,1,:) = [1 1 0 1];
% data(1,2,:) = [0 1 1 1];
% data(1,3,:) = [1 1 1 1];
% data(2,1,:) = [0 1 0 0];
% data(2,2,:) = [1 0 1 0];
% data(2,3,:) = [1 0 1 1];
% bins=[1 1 1 1;0 0 0 0;0 1 0 1];
% cnn(data, bins)

[M,N,K] = size(data);
[P, K1] = size(bins);
if (K ~= K1)
    error('dimension not match');
end

s = ones(M, N)*(P+1);
h = zeros(M, N);
for i = 1:P
    p = reshape(bins(i,:),1,1,K);
    d = repmat(p,[M,N,1]);
    b = sum(mod(d+data,2),3);
    ind = find(b < s);
    s(ind) = b(ind);
    h(ind) = i;
end

% h = zeros(M, N); % 1..P
% 
% for i = 1:M
%     for j = 1:N
%         d = reshape(data(i,j,:),1,K);
%         p = repmat(d,P,1);
%         b = sum(mod(p+bins, 2),2);
%         ind = find(b == min(b));
%         h(i,j) = ind(1);
%     end
% end

end